package com.ishow.bs.controller.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.ishow.bs.utils.MessageInfo;
import com.ishow.common.exception.ParameterException;
import com.ishow.common.utils.PageBean;

/**
 * 基础controller
 * 
 * @author chichi
 * @version 1.0
 */
public abstract class BaseController {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 获取分页对象
	 * 
	 * @param request
	 * @return
	 */
	protected PageBean getPageBean(HttpServletRequest request) {
		Integer pageIndex = request.getParameter("pageIndex") == null ? 0
				: Integer.valueOf(request.getParameter("pageIndex"));
		Integer pageSize = request.getParameter("pageSize") == null ? 10
				: Integer.valueOf(request.getParameter("pageSize"));
		PageBean pageBean = new PageBean(pageIndex, pageSize);
		return pageBean;
	}

	/**
	 * 获取排序
	 * 
	 * @param request
	 * @return
	 */
	protected String getSortName(HttpServletRequest request) {
		String sortName = request.getParameter("sortName") == null ? "1" : request.getParameter("sortName");
		if (sortName.length() > 30) {
			log.error("[SQL防注入]sortName参数长度超过制定的长度，sortName:" + sortName);
			return "1";
		} else {
			return sortName;
		}
	}

	/**
	 * 获取排序
	 * 
	 * @param request
	 * @return
	 */
	protected String getSortOrder(HttpServletRequest request) {
		String sortOrder = request.getParameter("sortOrder") == null ? "desc" : request.getParameter("sortOrder");
		if ("asc".equalsIgnoreCase(sortOrder) || "desc".equalsIgnoreCase(sortOrder)) {
			return sortOrder;
		} else {
			return "desc";
		}
	}

	/**
	 * 获取post请求body中的json数据
	 * 
	 * @param request
	 * @return
	 */
	protected JSONObject getPostData(HttpServletRequest request) {
		JSONObject result = null;
		try {
			StringBuffer data = new StringBuffer();
			String line = null;
			BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			while ((line = reader.readLine()) != null) {
				data.append(line);
			}
			if (data != null && !"".equals(data.toString().trim())) {
				result = JSONObject.parseObject(data.toString());
			}
		} catch (Exception e) {
			throw new ParameterException();
		}
		if (result == null) {
			throw new ParameterException();
		}
		return result;
	}

	/**
	 * 成功返回
	 * 
	 * @param object
	 * @return
	 */
	protected JSONObject success(Object object) {
		JSONObject result = MessageInfo.SUCCESS;
		result.put("msg_data", object);
		return result;
	}

}
